package com.kim.rssreader.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class RssHandler extends DefaultHandler {

	private static List<String> sinaRssCategory = new ArrayList<String>();
	private static List<String> ifengRssCategory = new ArrayList<String>();
	private List<String> currentRssContain = null;
	private String id = null;
	private HashMap<String, String> rssItem = null;

	private boolean isCategory = false;
	private boolean isStartRssItem = false;

	public void setIsCategory(boolean flag) {
		isCategory = flag;
	}

	public static boolean needsParser(int category) {
		if (category == RssSourceReader.RSS_CATEGORY_SINA) {
			if (sinaRssCategory.size() == 0) {
				return true;
			}
			return false;
		} else if (category == RssSourceReader.RSS_CATEGORY_IFENG) {
			if (ifengRssCategory.size() == 0) {
				return true;
			}
			return false;
		}
		return false;
	}

	public void setIsSina(boolean flag) {
		if (flag) {
			currentRssContain = sinaRssCategory;
		} else {
			currentRssContain = ifengRssCategory;
		}
	}

	public void setId(String id) {
		this.id = id;
		// isStartRssItem = true;
	}

	public String[] getRssCategory() {
		if (currentRssContain == null) {
			// didn't set witch category to laod.
			return null;
		}
		String[] rssArray = new String[currentRssContain.size()];
		for (int i = 0; i < rssArray.length; i++) {
			rssArray[i] = currentRssContain.get(i);
		}
		return rssArray;
	}

	public HashMap<String, String> getRssItems() {
		return this.rssItem;
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		String id = attributes.getValue("id");
		if (isCategory) {
			if (null != id) {
				if (currentRssContain == null) {
					// need set which category to load.
				} else {
					currentRssContain.add(id);
				}
			}
		} else {
			if (this.id.equals(id)) {
				isStartRssItem = true;
				rssItem = new HashMap<String, String>();
			}
			if (isStartRssItem) {
				String title = attributes.getValue("title");
				String xmlUrl = attributes.getValue("xmlUrl");
				if (xmlUrl != null) {
					rssItem.put(xmlUrl, title);
				}
			}
		}
		super.startElement(uri, localName, qName, attributes);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (localName.equals("category")) {
			isStartRssItem = false;
		}
		super.endElement(uri, localName, qName);
	}

}
